import { createRouter, createWebHistory } from 'vue-router'
import {useStore} from "@/stores/index.js";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      // 第一层路由就是登入界面
      path: '/',
      name: 'welcome',
      component: () => import('@/views/WelcomeView.vue'),
      // 子路由,登入的嵌套子路径
      children:[
        {
          path: '',
          name: 'welcome-login',
          component: () => import('@/components/welcome/LoginPage.vue')
        },{
          path: 'register',
          name: 'welcome-register',
          component: () => import('@/components/welcome/RegisterPage.vue')
        },{
          path: 'forgot',
          name: 'welcome-forgot',
          component: () => import('@/components/welcome/ForgotPage.vue')
        }
      ]
    },
    {
      // 登入之后的欢迎页
      path: '/index',
      name: 'index',
      component: () => import('@/views/IndexView.vue')
    }
  ]
})

// 路由守卫
router.beforeEach((to,from,next)=>{
  const store = useStore()
  // 如果用户已经登入了,但是想访问的界面是welcome-开头的就直接进入index
  if (store.auth.user !=null && to.name.startsWith('welcome-')){
    next('/index')
  }else if (store.auth.user =null && to.name.startsWith('index')){
    // 如果用户没有登入了,但是想访问的界面是index,直接丢回到登入界面
    next('/')
  }else if (to.matched.length === 0){
    //匹配的路径不存在,丢到index,index发现没有权限就会丢到最外层
    next('/index')
  }else {
    // 其他情况保持不变,该怎么路由就怎么路由
    next()
  }
})


export default router
